package com.sea.base.widget

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.FrameLayout
import com.sea.base.ext.global.obtainCancelMotionEvent

/**
 * 当子view有点击事件时，父的longClick会失效，这里支持自己的长按（效果和同一个view一致）
 */
class LongClickInterceptFrameLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
    FrameLayout(context, attrs, defStyleAttr) {

    private var callTouch = false
    private var isLongClickOk = false

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        //这里每次都给自己发一个Touch，如果触发长按就取消其他事件，这样就达到拦截长按的效果了
        callTouch = false
        val b = super.dispatchTouchEvent(if (isLongClickOk) obtainCancelMotionEvent() else ev)
        when (ev.action) {
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> isLongClickOk = false
        }
        if (!callTouch) {
            if (ev.action == MotionEvent.ACTION_UP) {
                onTouchEvent(obtainCancelMotionEvent())
            } else {
                onTouchEvent(ev)
            }
        }
        return b
    }

    override fun performLongClick(): Boolean {
        isLongClickOk = super.performLongClick()
        return isLongClickOk
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        callTouch = true
        return super.onTouchEvent(event)
    }
}